package com.example.myapplication;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.example.myapplication.pojo.IotDataObj;
import com.example.myapplication.pojo.Res;
import com.gsls.gt.GT;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class IotActivity extends AppCompatActivity {
    private TextView timestamp;
    private TextView Temperature;
    private TextView Humidity;
    private TextView ZhuoDu;
    private TextView Distance;
    private TextView GPS;
    private QMUITopBar mTopBar;
    private Handler handler;
    private Runnable runnable;

    private NotificationCompat.Builder builder;
    private static final int POLLING_INTERVAL = 3000; // 轮询间隔时间，单位为毫秒
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.iot_activity);
        ActionBar actionBar = getSupportActionBar();

        /*if (actionBar != null) {
            actionBar.hide();
        }*/
        mTopBar=findViewById(R.id.c_etopbar);
        QMUIStatusBarHelper.translucent(this);// 沉浸式状态栏
        initTopBar();//初始化状态栏

        Temperature=findViewById(R.id.Temperature);
        Humidity=findViewById(R.id.Humidity);
        ZhuoDu=findViewById(R.id.ZhuoDu);
        Distance=findViewById(R.id.Distance);
        Distance=findViewById(R.id.Distance);
        timestamp=findViewById(R.id.timestamp);
        GPS=findViewById(R.id.GPS);
    }

    private void initTopBar() {
        mTopBar.setBackgroundColor(ContextCompat.getColor(this, R.color.blue));
        mTopBar.setTitleGravity(Gravity.LEFT);
        mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
//                overridePendingTransition(R.anim.slide_still, R.anim.slide_out_right);
            }
        });

        /*mTopBar.setTitle("当前环境情况");*/
        updatedata();
        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                // 在这里执行你的网络请求操作
                new MyAsyncTask().execute();
                // 请求完成后，延迟一段时间再次发送请求
                handler.postDelayed(this, POLLING_INTERVAL);
            }
        };

        handler.post(runnable); // 启动轮询
    }

    private class MyAsyncTask extends AsyncTask<Void, Void, IotDataObj> {

        @Override
        protected IotDataObj doInBackground(Void... voids) {
            // 执行你的异步网络请求操作
            updatedata();
            // 返回请求结果，比如请求到的数据字符串
            return null;
        }
    }

    private void updatedata() {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("http://192.168.43.209:8883/iot/getcurrentdata")
                .method("GET", null)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.i("liaoyunfang", e.getMessage());
                Log.i("liaoyunfang", "error");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                String res = response.body().string();
                Res r = JSON.parseObject(res, Res.class);
                IotDataObj iotDataObj = JSON.parseObject(r.getData().toString(), IotDataObj.class);
                Log.i("liaoyunfang", "success");
                Log.i("liaoyunfang", iotDataObj.toString());

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        /*if (iotDataObj.getHumidity() > 70) {
                            builder.setContentText("当前湿度为" + iotDataObj.getHumidity() + "%，高于警戒值,请尽快采取措施");
                            GT.GT_Notification.startNotification(builder, 222);
                        }*/
                        Temperature.setText(String.valueOf(iotDataObj.getTemperature()) + "°C");
                        Humidity.setText(String.valueOf(iotDataObj.getHumidity()) + "%");
                        ZhuoDu.setText(String.valueOf(iotDataObj.getZhuoDu()) + "FTU");
                        Distance.setText(String.valueOf(iotDataObj.getDistance()) + "cm");
                        GPS.setText("(" + String.valueOf(iotDataObj.getGPSN()) + " , " + String.valueOf(iotDataObj.getGPSE()) + ")");
                        timestamp.setText(iotDataObj.getTimestamp().toString());
                    }
                });
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public  boolean onOptionsItemSelected(MenuItem item){

        int itemId = item.getItemId();
        Intent intent = new Intent();
        Log.i("liaoyunfang", String.valueOf(itemId));
        Log.i("liaoyunfang", String.valueOf(R.id.historical_data));
        if(itemId==R.id.historical_data){
            intent.setClass(IotActivity.this, IotHistoryActivity.class);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }
}